import colors from 'colors'
import semver from 'semver'
import log from '@start-cli-dev/log'

const LOWEST_NODE_VERSION = '16.0.0'
class Command {
  argv: any[]

  cmd: any

  constructor(args: any[]) {
    if (args.length < 1) {
      throw new Error('args不能为空数组')
    }
    this.argv = args

    new Promise(() => {
      let chain = Promise.resolve()
      chain = chain.then(() => this.checkNodeVersion())
      chain = chain.then(() => this.initArgs())
      chain = chain.then(() => this.init())
      chain = chain.then(() => this.exec())
      chain.catch(e => log.error('', e.message))
    }).catch(e => console.error('', e.message))
  }

  // 参数初始化
  initArgs() {
    const length = this.argv.length - 1
    this.cmd = this.argv[length]
    this.argv = this.argv.slice(0, length) // this.argv22 [ 'test-project', 'hah', { force: true, test: true } ]
  }

  // node 检查
  checkNodeVersion() {
    const currentVersion = process.version
    const lowestVersion = LOWEST_NODE_VERSION
    if (!semver.gte(currentVersion, lowestVersion)) {
      throw new Error(
        colors.red(
          `start-cli-dev 需要安装 v${lowestVersion} 及以上版本的 node.js`
        )
      )
    }
  }

  init() {
    throw new Error('init 方法必须实现')
  }

  exec() {
    throw new Error('exec 方法必须实现')
  }
}

export default Command
